import axios from 'axios';
import { history } from 'umi';
import qs from 'qs';
import SecurityService from './service/securityService';
const serverAddr = 'http://39.101.170.85:8082/';
// const serverAddr = 'http://10.8.21.134:8082/';
if (process.env.NODE_ENV === 'development') {
  axios.defaults.baseURL = '/service';
} else {
  axios.defaults.baseURL = serverAddr;
}

const instance = axios.create({
  headers: {
    'x-requested-with': 'XMLHttpRequest',
    'Content-Type': 'application/json',
  },
  transformRequest: (data: any, header: any) => {
    const type = header['Content-Type'];
    if (type && type === 'application/json') {
      return JSON.stringify(data);
    }
    return qs.stringify(data);
  },
});

instance.interceptors.request.use((request) => {
  const user: any = SecurityService.getSecurity();
  if (user && user.token) {
    request.headers = {
      ...request.headers,
      Authorization: user.token.loginToken,
    };
  }
  return request;
});
// instance.interceptors.request.use((request) => {
//   const token = window.localStorage.getItem('token');
//   if (token) {
//     request.headers = {
//       ...request.headers,
//       Authorization: token,
//     };
//   }
//   return request;
// });

instance.interceptors.response.use(
  (response) => {
    if (response.config.responseType === 'arraybuffer') {
      return response.data;
    }
    if (!response.data.success && response.data.code === 'FAILURE') {
      return Promise.reject({
        ...response.data,
        _response_headers_: response.headers,
      });
    } else if (
      !response.data.success &&
      response.data.code === 'UNAUTHORIZED'
    ) {
      history.replace('/401');
      return Promise.reject({
        ...response.data,
        _response_headers_: response.headers,
      });
    } else if (
      !response.data.success &&
      response.data.code === 'UNPERMISSION'
    ) {
      history.replace('/403');
      return Promise.reject({
        ...response.data,
        _response_headers_: response.headers,
      });
    }
    return {
      ...response.data,
      _response_headers_: response.headers,
    };
  },
  (error) => {
    if (error.response) {
      if (error.response.status === 401) {
        history.replace('/401');
      } else if (error.response.status === 403) {
        history.replace('/403');
      } else {
        history.replace('/500');
      }
      return Promise.reject({
        message: '服务器异常，请稍后重试',
        error: error.response,
      });
    }
    history.replace('/500');
    return Promise.reject({
      message: '服务器异常，请稍后重试',
      error,
    });
  },
);

export default instance;
export { serverAddr };
